package net.muhu.channel.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import net.muhu.domain.Location;
import net.muhu.domain.Musiverse;
import net.muhu.domain.ObjectFactory;

public class MusiverseServiceFileStorageImpl extends
		MusiverseServiceInMemoryImpl implements MusiverseServiceFileStorage {

	private JAXBContext jaxbContext;

	private Unmarshaller unmarshaller;

	private Marshaller marshaller;

	private File storage;

	public MusiverseServiceFileStorageImpl() throws JAXBException {
		jaxbContext = JAXBContext.newInstance(Musiverse.class);
		unmarshaller = jaxbContext.createUnmarshaller();
		marshaller = jaxbContext.createMarshaller();
	}

	@Override
	public void setFile(File storage) throws JAXBException {
		this.storage = storage;
		JAXBElement<Musiverse> musiverseElement = unmarshaller.unmarshal(
				new StreamSource(storage), Musiverse.class);
		musiverse = musiverseElement.getValue();
	}

	@Override
	public String addLocation(Location location) {
		try {
			String locationId = super.addLocation(location);
			save();
			return locationId;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void save() throws JAXBException, IOException {
		FileWriter writer = new FileWriter(storage);

		JAXBElement<Musiverse> musiverseElement = new ObjectFactory()
				.createMusiverse(musiverse);
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.marshal(musiverseElement, writer);

		writer.close();
	}
}
